package fxification.java;

import com.sun.javafx.functions.Function0;
import com.sun.javafx.functions.Function1;
import java.util.Timer;
import java.util.TimerTask;

public class ScheduledFxTaskRunner extends ATaskRunner{
    private long taskDelay, taskPeriod;
    private Timer timer;

    public ScheduledFxTaskRunner(long delay, long period){
        taskDelay = delay;
        taskPeriod = period;
    }

    @Override
    public void run(final TaskRunnerContext task) {
        if(task.getTaskWork() == null){
            throw new RuntimeException("Task has no work to be performed.  Provide a work function()");
        }

        if(task.isStarted()){
            return;
        }

        timer = new Timer("FxTaskRunner-"+this.hashCode());
        
        final TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                try{
                    signalTaskStart(task);
                    Object result = task.getTaskWork().invoke();
                    signalTaskCompletion(task, result);
                }catch(Throwable ex){
                    signalTaskError(task,ex);
                }
            }
        };

        // start timer task
        timer.schedule(timerTask, taskDelay, taskPeriod);
    }

    @Override
    public void stop(TaskRunnerContext task) {
        timer.cancel();
        timer = null;
        signalTaskStop(task);
    }
}